<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录页面</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="login-container">
        <div class="login-box">
            <h2>登录</h2>
            <form id="loginForm">
                <div class="input-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" required />
                </div>
                <div class="input-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" required />
                </div>
                <button type="submit" class="btn">登录</button>
                <p id="error-msg" style="color:red;"></p>
            </form>
        </div>
    </div>
    <script>
        document.getElementById('loginForm').addEventListener('submit', function (event) {
            event.preventDefault();

            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.href = '/'; // 登录成功后跳转到主页
                    } else {
                        const errorMsgElement = document.getElementById('error-msg');
                        errorMsgElement.innerText = '登录失败，请稍后重试！';
                        errorMsgElement.classList.add('shake');

                        // 移除动画类，以便下次可以再次触发
                        setTimeout(() => {
                            errorMsgElement.classList.remove('shake');
                        }, 820); // 动画持续时间 + 一点额外的时间
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    const errorMsgElement = document.getElementById('error-msg');
                    errorMsgElement.innerText = '登录失败，请稍后重试！';
                    errorMsgElement.classList.add('shake');

                    // 移除动画类，以便下次可以再次触发
                    setTimeout(() => {
                        errorMsgElement.classList.remove('shake');
                    }, 820); // 动画持续时间 + 一点额外的时间
                });
        });
    </script>
</body>

</html>